const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  type: {
    type: String,
    enum: ['daily', 'weekly', 'monthly', 'custom'],
    required: true
  },
  points: {
    type: Number,
    required: true,
    min: 0
  },
  completed: {
    type: Boolean,
    default: false
  },
  completedAt: {
    type: Date
  },
  nextAvailableAt: {
    type: Date
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

// 获取当前周的开始时间（周一凌晨）
function getStartOfWeek(date) {
  const d = new Date(date);
  const day = d.getDay();
  const diff = d.getDate() - day + (day === 0 ? -6 : 1); // 调整到周一
  d.setDate(diff);
  d.setHours(0, 0, 0, 0);
  return d;
}

// 获取当前周的结束时间（周日晚上）
function getEndOfWeek(date) {
  const d = new Date(getStartOfWeek(date));
  d.setDate(d.getDate() + 6);
  d.setHours(23, 59, 59, 999);
  return d;
}

// 检查任务是否可以完成
taskSchema.methods.canComplete = function() {
  const now = new Date();
  
  // 如果任务从未完成过，可以完成
  if (!this.completedAt) return true;
  
  const completedDate = new Date(this.completedAt);
  
  switch (this.type) {
    case 'daily':
      // 检查是否是同一天
      return now.getDate() !== completedDate.getDate() || 
             now.getMonth() !== completedDate.getMonth() || 
             now.getFullYear() !== completedDate.getFullYear();
    
    case 'weekly': {
      // 检查是否在同一周
      const currentWeekStart = getStartOfWeek(now);
      const completedWeekStart = getStartOfWeek(completedDate);
      return currentWeekStart.getTime() > completedWeekStart.getTime();
    }
    
    case 'monthly':
      // 检查是否在同一月
      return now.getMonth() !== completedDate.getMonth() || 
             now.getFullYear() !== completedDate.getFullYear();
    
    case 'custom':
      return !this.completed; // 自定义任务只能完成一次
    
    default:
      return false;
  }
};

// 获取下次可完成时间
taskSchema.methods.getNextAvailableTime = function() {
  if (!this.completedAt) return new Date();
  
  const completedDate = new Date(this.completedAt);
  
  switch (this.type) {
    case 'daily': {
      const tomorrow = new Date(completedDate);
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(0, 0, 0, 0);
      return tomorrow;
    }
    
    case 'weekly': {
      const nextWeek = getStartOfWeek(completedDate);
      nextWeek.setDate(nextWeek.getDate() + 7);
      return nextWeek;
    }
    
    case 'monthly': {
      const nextMonth = new Date(completedDate);
      nextMonth.setMonth(nextMonth.getMonth() + 1);
      nextMonth.setDate(1);
      nextMonth.setHours(0, 0, 0, 0);
      return nextMonth;
    }
    
    default:
      return new Date();
  }
};

// 完成任务
taskSchema.methods.complete = function() {
  if (!this.canComplete()) {
    const nextTime = this.getNextAvailableTime();
    throw new Error(`任务尚未到可完成时间，请等待至 ${nextTime.toLocaleString('zh-CN')}`);
  }
  
  const wasCompleted = this.completed;
  this.completed = true;
  this.completedAt = new Date();
  
  // 如果是第一次完成，或者是周期性任务，设置下次可完成时间
  if (!wasCompleted || ['daily', 'weekly', 'monthly'].includes(this.type)) {
    this.nextAvailableAt = this.getNextAvailableTime();
  }
  
  return this.save();
};

const Task = mongoose.model('Task', taskSchema);

module.exports = Task; 